package org.base.common.controller;

import cn.hutool.core.codec.Base64;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.base.common.VO.KaptchaVO;
import org.base.common.annotation.RequiredPerm;
import org.base.common.cache.CacheTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author He mingliang
 * @date 2020/8/16
 */
@Api(value = "验证码", tags = "验证码")
@RestController
@Slf4j
@AllArgsConstructor
public class KaptchaController {

    private CacheTemplate cacheTemplate;

    @RequestMapping("/kaptcha")
    @RequiredPerm(value = "anon", editable = false)
    public KaptchaVO getKaptchaImage() throws Exception {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48); // 图片的宽高
        captcha.setLen(2);  // 几位数运算，默认是两位
        captcha.getArithmeticString();  // 获取运算的公式：3+2=?
        final String result = captcha.text();// 获取运算的结果：5
        final String key = UUID.randomUUID().toString();
        cacheTemplate.set(key, result, 5, TimeUnit.MINUTES);
        try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
            // 输出图片流
            captcha.out(stream);
            final String base64Image = Base64.encode(stream.toByteArray());
            final KaptchaVO kaptchaVO = new KaptchaVO();
            kaptchaVO.setBase64Code(base64Image);
            kaptchaVO.setKey(key);
            return kaptchaVO;
        }
    }
}
